/**
 * 
 */
package com.dsp.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.core.util.AutoCompleteJSON;
import com.core.util.BaseUser;
import com.core.util.DspUtil;
import com.core.util.MD5;
import com.core.util.Pagination;
import com.dsp.bean.Message;
import com.dsp.bean.User;
import com.dsp.services.UserService;

/**
 * @author laker
 * 
 */
@Controller("UsersController")
public class UsersController extends DspController<User>{
	
	public UsersController() {
		super(User.class);
	}

	Logger logger = Logger.getLogger(DspUtil.Log4J);
	@Autowired
	private UserService userService;

	/**
	 * @RequestMapping(value="/users" ,method=RequestMethod.GET) public ModelAndView index(@RequestParam int c) {
	 *                                logger.info(UsersController.class + " currentPage : " + c ); Pagination<User> p =
	 *                                this.userService.find(new User() ,(c - 1) * Constants.pageSize , Constants.pageSize); p.setCurrent(c);
	 *                                p.setUrl("users"); ModelAndView mav = new ModelAndView(); mav.addObject(Constants.Pagination , p);
	 *                                mav.addObject(Constants.Path, "admin/user/list.jsp"); mav.setViewName("admin/user/list"); return mav;
	 *                                }
	 */
	/**
	 * 渲染一个页面
	 */
	@RequestMapping(value = "/users", method = RequestMethod.GET)
	public ModelAndView list() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("admin/user/list");
		mav.addObject("path", "admin/user/list.jsp");
		mav.addObject("current", "users");
		return mav;
	}

	@RequestMapping(value = "/users_list", method = RequestMethod.POST)
	@ResponseBody
	public Pagination<User> index(HttpServletRequest request, HttpServletResponse response) {
		int page = Integer.valueOf(request.getParameter("page"));
		int rp = Integer.valueOf(request.getParameter("rp"));
		String column = request.getParameter("qtype"); // 查询的列名
		String value = request.getParameter("query"); // 查询值

		DetachedCriteria dc = DetachedCriteria.forClass(User.class);
		if (!DspUtil.isEmpty(column) && !DspUtil.isEmpty(value)) {
			dc.add(Restrictions.like(column, value, MatchMode.ANYWHERE));
		}
		Pagination<User> p = this.userService.search(dc, (page - 1) * rp, rp);
		p.setPage(page);
		return p;
	}

	@RequestMapping(value = "/users_create", method = RequestMethod.POST)
	@ResponseBody
	public User create(@RequestBody User user) {
		logger.info(user.getUsername());
		logger.info(user.getShowname());
		logger.info(user.getPassword());
		logger.info(user.getEnabled());
		String md5_password = new MD5().getMD5ofStr(user.getPassword());
		user.setPassword(md5_password);
		try {
			if (user.getId() != null) {
				this.userService.update(user);
			} else {
				this.userService.save(user);
			}
		} catch (Exception se) {
			se.printStackTrace();
		}
		return user;
	}

	@RequestMapping(value = "/users_edit", method = RequestMethod.POST)
	@ResponseBody
	public User edit(@RequestBody User _user) {
		User user = this.userService.findById(_user.getId());
		return user;
	}
	
	@RequestMapping(value = "/update_password" , method = RequestMethod.POST)
	@ResponseBody
	public Message updatePassword(HttpServletRequest request, HttpServletResponse response){
		Message message = new Message();
		SecurityContextImpl upat = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		BaseUser bu = (BaseUser) upat.getAuthentication().getPrincipal();
		super.initHttp(request, response);
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		newPassword = DspUtil.req(newPassword, "");
		String confirmPass = request.getParameter("confirmPass");
		confirmPass = DspUtil.req(confirmPass, "");
		if (bu == null){
			super.initMessage(message, "连接超时,请重新登录.");
			return message;
		}
		if(newPassword.equals(confirmPass) == false){
			super.initMessage(message, "新密码与确认密码不一致,操作失败.");
			return message;
		}
		User user = this.userService.findById(bu.getId());
		oldPassword = new MD5().getMD5ofStr(oldPassword);
		newPassword = new MD5().getMD5ofStr(newPassword);
		if(user.getPassword().equals(oldPassword)){
			user.setPassword(newPassword);
			try {
				this.userService.update(user);
			} catch (Exception e) {
				e.printStackTrace();
				super.initMessage(message, e.getLocalizedMessage());
				return message;
			}
		} else {
			super.initMessage(message, "您输入的密码不对,操作失败");
			return message;
		}
		return message;
	}
	

	@RequestMapping(value = "/users_delete", method = RequestMethod.POST)
	@ResponseBody
	public void delete(@RequestBody User user) {
		this.userService.delete(user);
	}

	@RequestMapping(value = "/users_auto", method = RequestMethod.GET)
	@ResponseBody
	public AutoCompleteJSON<User> autocomplete(HttpServletRequest request, HttpServletResponse response) {
		String column = request.getParameter("column");
		String value = request.getParameter("value");
		AutoCompleteJSON<User> auto = new AutoCompleteJSON<User>();
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(User.class);
		detachedCriteria.add(Restrictions.like(column, value, MatchMode.ANYWHERE));
		List<User> ll = this.userService.likeBy(detachedCriteria);
		auto.setGeonames(ll);
		auto.setTotalResultsCount(ll.size());
		return auto;
	}

	/**
	 * 
	 */
	/**
	 * @param args
	 */
	public static void main(String[] args) {

	}

}
